@echo off
REM =============================
REM 配置变量（请根据实际调整）
REM =============================

setlocal enabledelayedexpansion

REM 项目名称
set "APP_NAME=cheese_everything"

REM 项目根目录（相对于当前脚本目录）
set "PROJECT_ROOT=%~dp0..\"
REM 去掉末尾的反斜杠
set "PROJECT_ROOT=%PROJECT_ROOT:~0,-1%"

REM JavaFX JMOD目录 、Azul21 JDK JMOD目录 runtime 输出目录 jpackage 输出目录
set "JAVAFX_JMOD=d:\soft\java\javafx21\openjfx-21.0.7\javafx-jmods-21.0.7"
set "AZUL_JMOD=d:\soft\java\azul.21\jmods"

set "RUNTIME_OUT=%PROJECT_ROOT%\dist\cheese-runtime-fatjar"
set "JPACKAGE_OUT=%PROJECT_ROOT%\dist\fatjar"

REM Maven 可执行文件（如果非默认，可指定全路径）
set "MVN_CMD=D:\soft\maven\apache-maven-3.9.9\bin\mvn"

REM 主jar名称（target 下）、主类全名
set "MAIN_JAR=cheese-everything-1.0-SNAPSHOT.jar"
set "MAIN_CLASS=com.cheese.everything.EverythingApplication"

REM icon地址
set "ICON_PATH=%PROJECT_ROOT%\script\static\icon.ico"

REM 模块列表
set "MODULES=javafx.controls,javafx.fxml"

REM =============================
REM 开始执行
REM =============================

echo project root path: !PROJECT_ROOT!
echo javafx jmod path: !JAVAFX_JMOD!
echo azul jmod path: !AZUL_JMOD!
echo runtime out path: !RUNTIME_OUT!
echo jpackage out path: !JPACKAGE_OUT!
echo main jar: !MAIN_JAR!
echo main class: !MAIN_CLASS!
echo cheese everything icon path: !ICON_PATH!

REM 设置 Java 环境
set "JAVA_HOME=d:\soft\java\azul.21"
set "PATH=%JAVA_HOME%\bin;%PATH%"

REM 进入项目根目录
cd /d "!PROJECT_ROOT!"

REM 打包清理
echo exec mvn clean package ...
call !MVN_CMD! clean package

REM 创建 app 目录并复制 jar
if not exist target\app mkdir target\app
copy target\!MAIN_JAR! target\app\
echo copy main jar success

REM ----- 临时注释
REM REM 复制依赖库
REM echo copy target\app\libs ...
REM call !MVN_CMD! dependency:copy-dependencies -DoutputDirectory=target\app\libs
REM echo generate app libs success

REM 生成 runtime
echo wait jlink generate runtime package ...
if exist "!RUNTIME_OUT!\" (
  echo Runtime directory "!RUNTIME_OUT!" already exists, remove directory
  rmdir /S /Q "!RUNTIME_OUT!"
)

echo running jlink Runtime directory "!RUNTIME_OUT!"
jlink --module-path "!AZUL_JMOD!;!JAVAFX_JMOD!" --add-modules !MODULES! --output "!RUNTIME_OUT!" --compress 2 --strip-debug --no-header-files --no-man-pages

REM 使用 jpackage 打包 MSI 安装包
echo wait jpackage package MSI ...
jpackage --runtime-image "!RUNTIME_OUT!" --input target\app --main-jar !MAIN_JAR! --main-class !MAIN_CLASS! --name !APP_NAME! --type msi --dest "!JPACKAGE_OUT!" --icon "!ICON_PATH!" --win-dir-chooser --win-menu --win-shortcut --java-options "-Dprism.order=sw"
if errorlevel 1 (
  echo jpackage failed
  pause
  exit /b 1
)
echo jpackage success
pause
